package cn.kongwg.java;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author kongwg
 * @create 2021-01-24 16:53
 */
@WebServlet("/uploadServlet")
public class UploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("收到文件");
        if (ServletFileUpload.isMultipartContent(req)){
            FileItemFactory fif = new DiskFileItemFactory();
           ServletFileUpload sfu = new ServletFileUpload(fif);

            try {
                List<FileItem> list = sfu.parseRequest(req);
                for (FileItem fi : list){
                    if (fi.isFormField()){
                        System.out.println("表单的名字"+fi.getFieldName());
                        System.out.println( "表单的值"+fi.getString("UTF-8"));
                    }else{
                        System.out.println("表单向的name属性值"+ fi.getFieldName());
                        System.out.println("上传文件的值"+ fi.getName());
                        fi.write(new File("E:\\"+fi.getName()));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
